<?php

namespace login\controller;

require_once("login/view/LoginView.php");
require_once("login/model/LoginModel.php");

class LoginController {

	/**
	 * @var \login\view\LoginView
	 */
	private $view;

	/**
	 * @var \login\model\LoginModel
	 */
	private $model;

	/**
	 * initiate member variables
	 * @param loginviewLoginView $view
	 */
	public function __construct(\login\view\LoginView $view, \common\model\BaseDAL $BaseDAL) {
		$this->model = new \login\model\LoginModel($BaseDAL);
		$this->view = $view;
	}

	/**
	 * if the session is set validate the session
	 * @return bool
	 */
	public function checkSession() {
		if ($this->model->checkSession()) {
			if ($this->model->validateSession()) {
				return true;
			}			
		}
		return false;
	}

	/**
	 * Try to login with either posted or cookie data
	 * @return void
	 */
	public function runLogin() {	
		//if user is logging out logout the view and the model
		if ($this->view->loggintOut()) {
			$this->view->logout();
			$this->model->logout();
		}
		else if ($this->view->userCookies()) {
			//if the user client has any cookies 
			try {
				//get the cookie data
				$userData = $this->view->getUserData();
				//login with the data from the cookies
				$this->model->login($userData);
				$this->view->loginSuccess();
			} catch (\Exception $e) {
				$this->view->loginFail();
			}
		}	
		if ($this->view->userLoggingIn()) {
			//if user is logging in
			try {
				//get posted data from view
				$userData = $this->view->getUserData();
				//validate and login with the posted data
				$this->model->login($userData);
				$this->view->loginSuccess();
			} catch (\Exception $e) {
				$this->view->loginFail();
			}
		}
	}
}

